package com.jingbian.cppccbackend.interceptors;

import com.jingbian.cppccbackend.utils.JwtUtil;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    // 定义管理员和用户token过期时间（小时和月）
    private static final long ADMIN_TOKEN_EXPIRE_HOURS = 1;
    private static final long USER_TOKEN_EXPIRE_DAYS = 30;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String token = request.getHeader("Authorization");
        
        // 判断是管理端还是用户端的请求
        boolean isAdminRequest = requestURI.startsWith("/admins");
        boolean isUserRequest = requestURI.startsWith("/users");
        
        // 如果既不是管理端也不是用户端的请求，则放行（如果有其他公共接口的话）
        if (!isAdminRequest && !isUserRequest) {
            return true;
        }

        try {
            if (token == null) {
                throw new RuntimeException("未登录");
            }

            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken == null) {
                throw new RuntimeException("登录已过期");
            }

            // 解析token
            Map<String, Object> claims = JwtUtil.parseToken(token);
            
            // 验证请求权限
            Boolean isSuperAdmin = (Boolean) claims.get("isSuperAdmin");
            String phone = (String) claims.get("phone");
            
            // 管理端请求必须使用管理员token
            if (isAdminRequest && isSuperAdmin == null) {
                throw new RuntimeException("无管理员权限");
            }
            
            // 用户端请求必须使用用户token
            if (isUserRequest && phone == null) {
                throw new RuntimeException("无用户权限");
            }

            // 刷新redis中token的过期时间
            if (isAdminRequest) {
                // 管理员token过期时间为1小时
                stringRedisTemplate.expire(token, ADMIN_TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
            } else if (isUserRequest) {
                // 用户token过期时间为30天
                stringRedisTemplate.expire(token, USER_TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
            }

            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
